﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;

namespace CSF.Utility.Security
{
    public static class AppCodec
    {
        public static string Encode(string appCode, string timeStamp)
        {
            byte[] key = GenerateKey(timeStamp);
            byte[] resultBytes = DESHelper.EncryptDES(timeStamp + appCode, key);

            return HttpServerUtility.UrlTokenEncode(resultBytes);
        }

        private static byte[] GenerateKey(string timeStamp)
        {
            byte[] result = Encoding.UTF8.GetBytes(timeStamp);
            if (result.Length != 8)
            {
                throw new ArgumentException("The length of argument timestamp must be 8.");
            }
            return result;
        }


        public static bool Decode(string encryptCode, string timeStamp, out string appCode)
        {
            byte[] key = GenerateKey(timeStamp);
            byte[] encryptBytes = HttpServerUtility.UrlTokenDecode(encryptCode);

            string decryptCode = DESHelper.DecryptDES(encryptBytes, key);

            if (decryptCode.StartsWith(timeStamp))
            {
                appCode = decryptCode.Substring(timeStamp.Length);
                return true;
            }
            appCode = string.Empty;
            return false;
        }

        public static string GetTimeStamp()
        {
            string result = DateTime.Now.Ticks.ToString();
            if (result.Length >= 8)
                return result.Substring(result.Length - 8);
            else
                return result.PadRight(8 - result.Length, '0');
        }
    }
}
